package com.echo.im.domain.group.message;

import com.echo.im.client.facade.IMClient;
import com.echo.im.common.model.message.IMGroupMessage;
import com.echo.im.infrastructure.mq.event.model.store.GroupStoreMessageEvent;
import com.echo.im.infrastructure.mq.event.producer.EventPublisher;
import com.echo.im.common.result.ResultEnum;
import com.echo.im.common.exception.GlobalException;
import com.echo.im.repository.dao.entity.GroupMessage;
import com.echo.im.repository.dao.mapper.GroupMessageMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: echo
 * @time: 2024-08-17
 */
@RequiredArgsConstructor
@Component
public class GroupMessageManager {

    private final IMClient imClient ;
    private final EventPublisher eventPublisher ;
    private final GroupStoreMessageEvent groupStoreMessageEvent;
    private final GroupMessageMapper groupMessageMapper;


    public  GroupMessage getAndCheckByMsgId(Long messageId) {
        GroupMessage message = groupMessageMapper.selectById(messageId);
        if (Objects.isNull(message)) {
            throw new GlobalException(ResultEnum.NO_MESSAGE);
        }
        return message;
    }


    public void sendAndSave(IMGroupMessage imGroupMessage) {
        sendAndSave(imGroupMessage,true);
    }

    public void send(IMGroupMessage imGroupMessage) {
        sendAndSave(imGroupMessage,false);
    }


    public void sendAndSave(IMGroupMessage imGroupMessage,Boolean isStore) {
        imClient.sendMessage(imGroupMessage);
        if (isStore){
            //持久化
            eventPublisher.publish(groupStoreMessageEvent,imGroupMessage.getData());
        }
    }

}
